package cn.kgc.springboot.vue.shiro;

import cn.hutool.json.JSONUtil;
import cn.kgc.springboot.vue.response.ResponseResult;
import cn.kgc.springboot.vue.response.ResponseStatus;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/12/25
 * @description  自定义filter  校验token的合法性
 */
public class JwtTokenFilter extends BasicHttpAuthenticationFilter {

    // 判定经过当前过滤器的请求是否放行   true  放行   false 拦截
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("-----------isAccessAllowed-------------");
        // 判定token是否合法
        try {
            executeLogin(request,response);
            return true;
        } catch (Exception e) {
           e.printStackTrace();
            ResponseResult message = ResponseResult.fail().code(ResponseStatus.UN_AUTH).message(ResponseStatus.UN_AUTH.getMessage());
            String result = JSONUtil.toJsonStr(message);
            PrintWriter writer = null;
            try {
                HttpServletResponse resp = (HttpServletResponse) response;
                resp.setContentType("application/json;charset=utf-8");
                writer = resp.getWriter();
                writer.write(result);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }finally {
                if (writer!=null){
                    writer.close();
                }
            }
            return  false;
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {

        System.out.println("---------executeLogin------------");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("authentication");
        if (StringUtils.isBlank(token)){
            throw  new RuntimeException("token异常...");
        }

        Subject subject = getSubject(request, response);
        // token  login()
        JwtToken jwtToken = new JwtToken(token,request);

        subject.login(jwtToken);
        return true;
    }
}
